package ru.magicreader.server.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

/*
 * User of the service.
 */
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class User implements Serializable {
	private static final long serialVersionUID = 1L;

	@Persistent
	@PrimaryKey
	private String login;
	
	@Persistent
	private ArrayList<Feed> feeds = new ArrayList<Feed>();
	
	@NotPersistent
	private String logoutUrl;
	
	@Persistent
	private Settings settings = new Settings();
	
	@Persistent
	private Integer nVisits = new Integer(0);
	
	public User(String login) {
		this.login = login;
	}
	
	public void setLogin(String login) {
		this.login = login;
	}

	public String getLogin() {
		return login;
	}

	public List<Feed> getFeeds() {
		return feeds;
	}
	
	public void setLogoutUrl(String logoutUrl) {
		this.logoutUrl = logoutUrl;
	}

	public String getLogoutUrl() {
		return logoutUrl;
	}

	public void setSettings(Settings settings) {
		this.settings = settings;
	}

	public Settings getSettings() {
		return settings;
	}

	public void incrementNumberOfVisits() {
		if(nVisits != null)
			nVisits = nVisits.intValue() + 1;
		else
			nVisits = new Integer(1);
	}

	public Integer getNumberOfVisits() {
		return nVisits;
	}

	public String toJson() {
		StringBuilder ret = new StringBuilder();
		ret.append("{\n" +
			"\"login\": \"" + login + "\",\n" +
			"\"logoutUrl\": \"" + logoutUrl + "\",\n");
		
		if(settings != null) {
			ret.append("\"settings\": " + settings.toJson() + ",\n");
		}
			
		ret.append("\"feeds\":\n" +
			"[\n");
		
		for(int i = 0; i < feeds.size(); i++) {
			ret.append(feeds.get(i).toJson());
			if(i != feeds.size() - 1) { ret.append(','); }
		}
		
		ret.append("]\n" +
		"}\n");
		
		return ret.toString();
	}

}
